cc.Class({
   extends: cc.Component,

   properties: {
        winLabel : {
            default: null,
            type: cc.Node
        },
        startLabel : {
            default: null,
            type: cc.Node
        },

        // 这个属性引用了星星预制资源
        starPrefab: {
            default: null,
            type: cc.Prefab
        },
        // 星星产生后消失的时间
        starDuration: 0,
        // 地面节点，用于确定星星生成的高度
        ground: {
            default: null,
            type: cc.Node
        },
        // player 节点，用于获取主角弹跳的高度，和控制主角行动开关
        player1: {
            default: null,
            type: cc.Node
        },
        player2: {
            default: null,
            type: cc.Node
        },
        //得分节点
        score1:0,
        score2:0,
        scoreDisplay1: {
            default: null,
            type: cc.Label
        },
        scoreDisplay2: {
            default: null,
            type: cc.Label
        },
       //房间号板
        roomidDisplay : cc.Label,

        //上一次的星星的横坐标位置
        starX : 0,
       //每次星星生成的最小间距
        starDistance : 100,

        //得分的声音
        scoreAudio: {
            default: null,
            url: cc.AudioClip
        },
       //游戏时长
        timeLength: 0,

       //退出按钮
        exitLabel : cc.Node,
       // 提示消息板 等待对手加入什么的
       noticeLabel: cc.Label,
        showNoticeClear :0,
       //顶部游戏倒数计时
        gameTime:cc.Label,
       //各种音效
       //胜利
       winAudio:cc.AudioClip,
       //失败
       loseAudio:cc.AudioClip,
       //平局
       drawnAudio:cc.AudioClip
    },
    wx_share: function(){
        if (!Global.isWeiXin()) return;

        //修改微信的分享给朋友时的界面
        if (Global.isRand == false) {
            var xhr = new XMLHttpRequest();
            var url = "/index/wechat/ajaxSignPackage";
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                    var wxoptions = {
                        sign_pkg: JSON.parse(xhr.responseText),
                        wx_share: {
                            "title": "K米蹦笨跳",
                            "desc": "看谁吃的星星更多,快来试试看",
                            "link": location.origin + location.pathname +"?roomid=" + Global.roomId,
                            "imgurl": "/static/common/images/star.png"
                        }
                    }
                    initWeiXin(wxoptions);
                }
            };
            xhr.open("GET", url+"?url="+encodeURIComponent(window.location.href), true);
            xhr.send();
        }
    },
    onLoad: function(){
        var state = {
            title: "title",
            url: "#"
        };
        window.history.pushState(state, "title", "#");
        window.addEventListener("popstate", function() {
            //当IOS按返回时,直接关闭窗口并断开ws连接
            Global.ws.close();
            window.WeixinJSBridge.call('closeWindow');
        })


        clearInterval(Global.login.showNoticeClear);
        clearInterval(this.showNoticeClear);

        // 获取地平面的 y 轴坐标
        this.groundY = this.ground.y + this.ground.height/2;

        if (Global.myRole == 1) {
            Global.playerSelf = this.player1.getComponent('Player');
            Global.playerChallenger = this.player2.getComponent('Player');
            this.scoreSelf = this.scoreDisplay1;
            this.scoreChallenger = this.scoreDisplay2;
        } else {
            Global.playerSelf = this.player2.getComponent('Player');
            Global.playerChallenger = this.player1.getComponent('Player');
            this.scoreSelf = this.scoreDisplay2;
            this.scoreChallenger = this.scoreDisplay1;
        }
        Global.playerSelf.node.active = true;
        if (Global.isJoin == true) {
            Global.playerChallenger.node.active = true;
        }
        Global.game = this;

        if (Global.isRand == true) {
            if (Global.isJoin == false) {
                this.showNotice("正在等待对手加入");
                this.noticeLabel.node.active = true;
            }
            this.roomidDisplay.node.active = false;
        } else {
            if (Global.isJoin == false) {
                this.noticeLabel.string = '点击右上角邀请朋友\n一起来玩吧!';
                this.noticeLabel.node.active = true;
            }
            this.roomidDisplay.string = "Room ID:" + Global.roomId;
        }

        if (Global.isJoin == true) {
            var sendData = {
                type: "challengerJoinRoom",
            }
            var sendString = JSON.stringify(sendData);
            Global.ws.send(sendString);

            var sendData = {
                type: "gameStart",
                jumpHeight: Global.playerSelf.jumpHeight,
                groundY: Global.game.groundY,
                starDistance: Global.game.starDistance
            }
            var sendString = JSON.stringify(sendData);
            Global.ws.send(sendString);
        }

        this.wx_share();
    },
    readyCountDown: function(){
        this.startLabel.active = false;
        this.exitLabel.active = false;
        cc.find("Canvas/countDown").getComponent('CountDown').countDown();
    },
    cocosLoad: function () {
        Global.gameover = false;
        this.gameTime.string = "剩余时间:" + this.timeLength;

        //分数置0
        this.score1 = 0;
        this.score2 = 0;

        this.scoreSelf.string = "我的分数:0";
        this.scoreChallenger.string = "对手分数:0";
        
        //按键隐藏
        this.startLabel.active = false;
        this.exitLabel.active = false;
        this.scoreDisplay1.node.active = true;
        this.scoreDisplay2.node.active = true;
        this.gameTime.node.active = true;
        this.roomidDisplay.node.active = false;

        //启动自己的角色的动作监听 同时把动作上传到服务器
        Global.playerSelf.selfLoad();
        Global.playerChallenger.chanllengerLoad();
        this.gameCountDown();
    },
    gameCountDown: function() {
        var self = this;
        var timeLength = this.timeLength;
        var clear = setInterval(function(){
            timeLength -= 1;
            self.gameTime.string = "剩余时间:" + timeLength;
            if (timeLength == 0) {
                self.gameOver();
                clearInterval(clear);
            }
        }, 1000);
    },
   //生成一个新的星星 由服务器生成
    spawnNewStar: function(x,y) {
        //另一个没吃到星星的玩家 销毁旧的星星
        var star = cc.find("Canvas/star");
        if (star != null) {
            star.destroy();
        }
        // 使用给定的模板在场景中生成一个新节点
        var newStar = cc.instantiate(this.starPrefab);
        // 将新增的节点添加到 Canvas 节点下面
        this.node.addChild(newStar);
        // 为星星设置一个随机位置
        newStar.setPosition(x,y);

        newStar.getComponent('Star').game = Global.game;

    },

    //自己加分
    gainScore: function(addScroe) {
        addScroe = addScroe  || 1;
        this.score1 += addScroe;
        this.scoreSelf.string = "我的分数:" + this.score1.toString();
        Global.audioPlay(this.scoreAudio);
    },
    //对手加分
    challengerGainScore: function(addScroe) {
        addScroe = addScroe  || 1;
        this.score2 += addScroe;
        this.scoreChallenger.string = "对手分数:" + this.score2.toString();
    },
    //游戏结束
    gameOver : function() {
        Global.gameover = true;
        if (Global.isJoin == true) {
            this.exitLabel.active = true;

            var sendData = {
                type: "gameOver"
            };
            var sendString = JSON.stringify(sendData);
            Global.ws.send(sendString);
        }

        //移除重复的跳跃动作
        Global.playerSelf.gameOver();
        Global.playerChallenger.gameOver();

        //显示胜利/失败  房主显示开始按钮
        var winCp = this.winLabel.getComponent(cc.Label);

        if (this.score1 > this.score2) {//胜利
            winCp.string = "You Win";
            Global.audioPlay(this.winAudio);
        } else if(this.score1 < this.score2){//失败
            winCp.string = "You Lose";
            Global.audioPlay(this.loseAudio);
        } else {//平局
            winCp.string = "Drawn";
            Global.audioPlay(this.drawnAudio);
        }
        this.winLabel.active = true;

        if (Global.isJoin == false) {
            this.startLabel.active = true;
        }

        var star = cc.find("Canvas/star");
        if (star != null) {
            star.destroy();
        }
    },
    showNotice : function(content) {
        var n = 0;
        var self = this;
        Global.game.showNoticeClear = setInterval(function(){
            if (self.noticeLabel == null) return;
            switch (n%3) {
                case 0:
                    self.noticeLabel.string = content + ".";
                    break;
                case 1:
                    self.noticeLabel.string = content + "..";
                    break;
                case 2:
                    self.noticeLabel.string = content + "...";
                    break;
            }
            n ++;
        },700);
    },
    update: function() {
    }
});